using System;
using System.Collections.Generic;
using UnityEngine;

namespace Super
{
	[RequireComponent(typeof(Collider2D))]
	public class SpriteBtn : MonoBehaviour
	{
		private Vector3 oriScale;
		public Vector3 scale = new Vector3(0.9f, 0.9f, 0.9f);
		//是否在鼠标进入 会让操作卡顿，先取消相关代码
		public bool isEnter;
		public Dictionary<MouseKey, Action> actionDict = new Dictionary<MouseKey, Action>()
		{
			{MouseKey.Left, null},
			{MouseKey.Middle, null},
			{MouseKey.Right, null},
		};
		
		public void OnEnable()
		{
			EventManager.Register<MouseDownGE>(OnMouseDownGE);
			EventManager.Register<MouseUpGE>(OnMouseUpGE);
		}

		private void Start()
		{
			oriScale = transform.localScale;
		}
		
		public void SetAction(MouseKey key, Action action)
		{
			actionDict[key] = action;
		}

		private void OnMouseEnter()
		{
			if (InputManager.Ins.mouseInfo.isHold) return;
			if (InputManager.Ins.isMouseOverUI) return;
			isEnter = true;
		}
		
		private void OnMouseOver()
		{
			if (InputManager.Ins.mouseInfo.isHold) return;
			if (InputManager.Ins.isMouseOverUI) return;
			isEnter = true;
		}

		private void OnMouseExit()
		{
			isEnter = false;
			transform.localScale = oriScale;
		}
		
		//不可用OnMouseDown代替，因为它不会触发右键点击
		public void OnMouseDownGE(MouseDownGE evt)
		{
			if (!isEnter) return;
			if (InputManager.Ins.isMouseOverUI) return;

			transform.localScale = Vector3.Scale(oriScale, scale);
		}
		
		public void OnMouseUpGE(MouseUpGE evt)
		{
			if (!isEnter) return;
			if (InputManager.Ins.isMouseOverUI) return;
			transform.localScale = oriScale;
			
			MouseKey holdKey = InputManager.Ins.mouseInfo.holdKey;
			actionDict[holdKey]?.Invoke();
			EventManager.Emit(new BtnClick());
		}

		private void OnDestroy()
		{
			EventManager.UnRegisterAll(this);
		}
		
		private void OnDisable()
		{
			EventManager.UnRegisterAll(this);
		}
	}
}
